package com.ruoyi.interceptor;


import com.ruoyi.domain.common.UserHolder;
import com.ruoyi.utils.JJWTUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: lsx
 * @Description: 解析token，获取id，存储到UserHolder(本质是LocalThread)中
 * @Create:  2025/1/7 9:50
 **/
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(!"null".equals(token) && StringUtils.hasLength(token)){
            if(JJWTUtils.verifyToken(token)){
                Jws<Claims> claimsJws = JJWTUtils.parseJWT(token);
                String id = claimsJws.getBody().get("id").toString();
                log.info("解析token成功，id = {}",id);
                UserHolder.setUserId(Double.valueOf(id).intValue());
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeThreadLocal();
    }
}